package com.enjoy.concurrent.ch11;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;

/**
 * -XX:BiasedLockingStartupDelay=0
 * 关闭偏向延迟
 * -XX:+UseBiasedLocking
 * 启用偏向锁
 * -XX:-UseBiasedLocking
 * 关闭偏向锁
 */
@Slf4j
public class JOLTest {

    private static final A a = new A();

    @Test
    public void test1() throws InterruptedException {
        new Thread(() -> {
            log.info("开始执行:" + ClassLayout.parseInstance(a).toPrintable());
            synchronized (a) {
                log.info("获取锁执行中:" + ClassLayout.parseInstance(a).toPrintable());
            }
            log.info("释放锁:" + ClassLayout.parseInstance(a).toPrintable());
        }, "t1").start();
        //防止退出
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test
    public void test2() throws InterruptedException {
        // -XX:BiasedLockingStartupDelay=0 -XX:+UseBiasedLocking
        new Thread(() -> {
            log.info("开始执行:" + ClassLayout.parseInstance(a).toPrintable());
            synchronized (a) {
                log.info("获取锁执行中:" + ClassLayout.parseInstance(a).toPrintable());
            }
            log.info("释放锁:" + ClassLayout.parseInstance(a).toPrintable());
        }, "t1").start();

        Thread.sleep(4000);

        new Thread(() -> {
            log.info("开始执行:" + ClassLayout.parseInstance(a).toPrintable());
            synchronized (a) {
                log.info("获取锁执行中:" + ClassLayout.parseInstance(a).toPrintable());
            }
            log.info("释放锁:" + ClassLayout.parseInstance(a).toPrintable());
        }, "t2").start();

        //防止退出
        Thread.sleep(Integer.MAX_VALUE);
    }

    public static void main(String[] args) throws InterruptedException {
        // -XX:BiasedLockingStartupDelay=0 -XX:+UseBiasedLocking
        new Thread(() -> {
            log.info("开始执行:" + ClassLayout.parseInstance(a).toPrintable());
            synchronized (a) {
                log.info("获取锁执行中:" + ClassLayout.parseInstance(a).toPrintable());
            }
            log.info("释放锁:" + ClassLayout.parseInstance(a).toPrintable());
        }, "t1").start();

        Thread.sleep(4000);

        new Thread(() -> {
            log.info("开始执行:" + ClassLayout.parseInstance(a).toPrintable());
            synchronized (a) {
                log.info("获取锁执行中:" + ClassLayout.parseInstance(a).toPrintable());
            }
            log.info("释放锁:" + ClassLayout.parseInstance(a).toPrintable());
        }, "t2").start();

        //防止退出
        Thread.sleep(Integer.MAX_VALUE);
    }
}
